package com.test.redis.controller;

import com.test.redis.entity.DataSourceConfig;
import com.test.redis.entity.DataSourceMessage;
import com.test.redis.service.DataSourceConfigMapper;
import com.test.redis.service.DynamicDataSourceManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 数据源管理控制器
 * 提供数据源配置的REST API
 */
@Slf4j
@RestController
@RequestMapping("/api/datasource")
public class DataSourceController {
    
    @Autowired
    private DataSourceConfigMapper dataSourceConfigMapper;
    
    @Autowired
    private DynamicDataSourceManager dataSourceManager;
    
    /**
     * 获取所有数据源配置
     */
    @GetMapping("/configs")
    public List<DataSourceConfig> getAllConfigs() {
        return dataSourceConfigMapper.selectList(null);
    }
    
    /**
     * 根据ID获取数据源配置
     */
    @GetMapping("/config/{id}")
    public DataSourceConfig getConfigById(@PathVariable Long id) {
        return dataSourceConfigMapper.selectById(id);
    }
    
    /**
     * 创建数据源配置
     */
    @PostMapping("/config")
    public String createConfig(@RequestBody DataSourceConfig config) {
        dataSourceConfigMapper.insert(config);
        
        // 如果数据源是启用状态，则创建数据源并发布消息
        if (config.getStatus() == 1) {
            dataSourceManager.createDataSource(config);
            dataSourceManager.publishDataSourceChange(DataSourceMessage.MessageType.CREATE, config.getName());
        }
        
        return "数据源配置创建成功";
    }
    
    /**
     * 更新数据源配置
     */
    @PutMapping("/config/{id}")
    public String updateConfig(@PathVariable Long id, @RequestBody DataSourceConfig config) {
        config.setId(id);
        dataSourceConfigMapper.updateById(config);
        
        // 发布数据源更新消息
        dataSourceManager.publishDataSourceChange(DataSourceMessage.MessageType.UPDATE, config.getName());
        
        return "数据源配置更新成功";
    }
    
    /**
     * 删除数据源配置
     */
    @DeleteMapping("/config/{id}")
    public String deleteConfig(@PathVariable Long id) {
        DataSourceConfig config = dataSourceConfigMapper.selectById(id);
        if (config != null) {
            dataSourceConfigMapper.deleteById(id);
            
            // 发布数据源删除消息
            dataSourceManager.publishDataSourceChange(DataSourceMessage.MessageType.DELETE, config.getName());
        }
        
        return "数据源配置删除成功";
    }
    
    /**
     * 刷新所有数据源
     */
    @PostMapping("/refresh")
    public String refreshAllDataSources() {
        dataSourceManager.publishDataSourceChange(DataSourceMessage.MessageType.REFRESH_ALL, "");
        return "已发送刷新所有数据源的指令";
    }
    
    /**
     * 获取当前活跃的数据源列表
     */
    @GetMapping("/active")
    public List<String> getActiveDataSources() {
        return dataSourceManager.getDataSourceNames();
    }
}